#!/bin/sh

# Copyright (c) 2006-2007 XenSource, Inc.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# Allow the path to the 'xe' binary to be overridden by the XE environment variable
if [ -z "${XE}" ]; then
  XE=xe
fi

if [ ! -e "${HOME}/.xe" ]; then
  read -p "Server name: " SERVER
  read -p "Username: " USERNAME
  read -p "Password: " PASSWORD
  XE="${XE} -s ${SERVER} -u ${USERNAME} -pw ${PASSWORD}"
fi

# Check there's a vm uuid parameter to the command
if [ $# -ne 1 ]; then
	echo "usage: $0 <vm_uuid_to_suspend_and_resume>"
	exit 1
fi
vmuuid=$1

# Check if there's a VM by the uuid specified
${XE} vm-list params=uuid | grep -q " ${vmuuid}$"
if [ $? -ne 0 ]; then
	echo "error: no vm uuid \"${vmuuid}\" found"
	exit 2
fi

# Check that it's running
POWERSTATE=`${XE} vm-param-get uuid=${vmuuid} param-name=power-state`

if [[ ${POWERSTATE} != "running" ]]; then
        echo "error: vm must be running in order for it to suspend. State is currently '${POWERSTATE}'"
	exit 2
fi

# Now let's suspend the VM
echo "Suspending VM..."
${XE} vm-suspend uuid=${vmuuid} 

# VMs get their memory image written into a VDI. The SR in which the VDI is 
# created is set in the host field: "suspend-image-sr-uuid"
VDI=`${XE} vm-param-get uuid=${vmuuid} param-name=suspend-VDI-uuid`
echo "Suspended. VDI containing image has uuid: ${VDI}"

POWERSTATE=`${XE} vm-param-get uuid=${vmuuid} param-name=power-state`
echo "State is now '${POWERSTATE}'"

# Resume the VM
echo "Resuming..."
${XE} vm-resume uuid=${vmuuid}



